import requests


class Tieba:
    def __init__(self, name, count):
        #
        self.name = name
        #
        self.count = count

        self.url_list = []
        for i in range(self.count):
            # 爬取的地址
            self.url_list.append('https://tieba.baidu.com/f?kw={}&pn={}'.format(self.name, i * 50))

        # 定义请求头
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36'
        }

    def get_data(self, url):
        # 获取数据的方法
        response = requests.get(url, headers=self.headers)
        return response.content.decode('utf-8')

    def process_data(self, data, num):
        # 处理数据
        with open('tieba_{}_{}.html'.format(self.name, num), 'w', encoding='utf-8')as f:
            f.write(data)

    def start(self):

        for num, url in enumerate(self.url_list):
            # 获取数据
            data = self.get_data(url)
            # 处理数据
            self.process_data(data, num + 1)


if __name__ == '__main__':
    t = Tieba('皮卡丘', 3)
    t.start()
    t = Tieba('灌篮高手', 5)
    t.start()
